package com.cy.linklist;

/**
 * @Author: chenyun
 * @Date: 2021/09/15/17:11
 * @Description:
 */

//剑指 Offer 24 反转链表

//定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点
// 1->2->3->null     null<-1<-2<-3
public class Demo24 {
    public static ListNode reverseList(ListNode head) {
        ListNode pre = null;  // 指向最后一个节点null
        ListNode cur = head;  // 指向头节点1
        while (cur!=null){
            ListNode tem = cur.next;    // 暂存后继节点 cur.next
            cur.next = pre;             // 修改 next 引用指向
            pre = cur;                  // pre 暂存 cur
            cur = tem;                  // cur 访问下一节点
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = null;
        ListNode head = listNode1;
        System.out.println("链表显示数据顺序");
        while (head != null){
            System.out.print(head.val);
            head = head.next;
        }
        ListNode nodes = reverseList(listNode1);
        System.out.println();
        System.out.println("链表从尾到头的数据");
        while (nodes != null){
            System.out.print(nodes.val);
            nodes = nodes.next;
        }
    }
}
